import cv2
import pytesseract
import numpy as np
import os

# 定义图片路径
image_path = r'd:\tmp\full3.png'

# 定义处理的 y 坐标区间
y_min = 219
y_max = 853

# 检查文件是否存在
if not os.path.exists(image_path):
    print(f"文件 {image_path} 不存在，请检查路径。")
else:
    # 读取图片
    image = cv2.imread(image_path)
    # 只截取指定 y 坐标区间的图像
    roi_image = image[y_min:y_max, :]
    gray = cv2.cvtColor(roi_image, cv2.COLOR_BGR2GRAY)

    # 使用 pytesseract 进行文字识别
    data = pytesseract.image_to_data(gray, output_type=pytesseract.Output.DICT)

    # 定义一个列表来存储识别到的有效文字区域及对应的文字
    regions_with_text = []

    # 遍历识别到的文字，过滤掉无文字区域
    for i in range(len(data['text'])):
        x, y, w, h = data['left'][i], data['top'][i], data['width'][i], data['height'][i]
        text = data['text'][i].strip()
        if text:
            # 恢复原始的 y 坐标
            actual_y = y + y_min
            regions_with_text.append((x, actual_y, x + w, actual_y + h, text))

    # 定义合并区域的水平距离阈值
    horizontal_threshold = 30  # 可根据实际情况调整

    # 水平方向的合并函数
    def merge_horizontally(regions, threshold):
        merged = []
        while regions:
            current = regions.pop(0)
            merged_region = list(current)
            i = 0
            while i < len(regions):
                other = regions[i]
                # 计算水平距离
                horizontal_distance = min(abs(merged_region[2] - other[0]), abs(other[2] - merged_region[0]))
                # 检查是否在同一行（垂直方向有重叠）
                vertical_overlap = max(merged_region[1], other[1]) < min(merged_region[3], other[3])
                if horizontal_distance < threshold and vertical_overlap:
                    # 更新合并区域的坐标
                    merged_region[0] = min(merged_region[0], other[0])
                    merged_region[1] = min(merged_region[1], other[1])
                    merged_region[2] = max(merged_region[2], other[2])
                    merged_region[3] = max(merged_region[3], other[3])
                    # 拼接文字
                    merged_region[4] += " " + other[4]
                    regions.pop(i)
                else:
                    i += 1
            merged.append(tuple(merged_region))
        return merged

    # 进行水平合并
    merged_regions_with_text = merge_horizontally(regions_with_text, horizontal_threshold)

    # 打印识别区域的文字和中心点坐标，以及以冒号结尾区域右侧 +50 像素的位置坐标
    for region in merged_regions_with_text:
        x1, y1, x2, y2, text = region
        center_x = (x1 + x2) // 2
        center_y = (y1 + y2) // 2
        input_box_info = ""
        if ':' in text:
            # 计算右侧 +50 像素的位置坐标
            right_x = x2 + 50
            # 确保右侧坐标不超出图像范围
            right_x = min(right_x, image.shape[1] - 1)
            input_box_center_y = (y1 + y2) // 2
            input_box_info = f", 输入框大致位置坐标: ({right_x}, {input_box_center_y})"
            # 在输入框大致位置画红色小圆圈
            cv2.circle(image, (right_x, input_box_center_y), 5, (0, 0, 255), -1)

        print(f"文字: {text}, 中心点坐标: ({center_x}, {center_y}){input_box_info}")

    # 在图片上绘制绿色边框
    for region in merged_regions_with_text:
        x1, y1, x2, y2, _ = region
        cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)

    # 显示图片
    cv2.imshow('Image with Regions', image)

    # 等待任意键退出
    cv2.waitKey(0)
    cv2.destroyAllWindows()